package com.camunda.workflow.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjUtil;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.IdentityService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.runtime.ActivityInstance;
import org.camunda.bpm.engine.runtime.Execution;
import org.camunda.bpm.engine.variable.VariableMap;
import org.camunda.bpm.engine.variable.Variables;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
public class ProcessController {
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private IdentityService identityService;

    @PostMapping("/start/{processKey}")
    public void start(@PathVariable(value = "processKey") String processKey, @RequestBody Map<String, Object> vars) {
        VariableMap variables = Variables.createVariables();
        if(MapUtil.isNotEmpty(vars)){
            String starter = (String)vars.get("starter");
            if(ObjUtil.isNotEmpty(starter)){
                identityService.setAuthenticatedUserId(starter);
                vars.remove("starter");
            }
            List<String> leaders = (List<String>)vars.get("leaders");
            if(CollUtil.isNotEmpty(leaders)){
                variables.put("leaders",leaders);
                vars.remove("leaders");
            }
            vars.forEach(variables::putValue);
        }
        runtimeService.startProcessInstanceByKey(processKey, variables);
    }

    @GetMapping("/executions/{processInstanceId}")
    public List<Execution> getAllExecutions(@PathVariable(value = "processInstanceId") String processInstanceId) {
        List<Execution> list = runtimeService.createExecutionQuery().processInstanceId(processInstanceId).list();
        log.info("executions:{}", list.size());
        ActivityInstance activityInstance = runtimeService.getActivityInstance(processInstanceId);
        log.info("ActivityInstance ID :{}", activityInstance.getActivityId());
        return list;
    }
}
